<?php
namespace app\admin\controller;

class Documents extends Admin {

	/**
	 * 文档管理
	 * @return [type] [description]
	 */
	public function index() {
		//查询全部分类
		$mSort = D('api/Sorting');
		$sort = $mSort->field('id,sname,pid')->where(['tmp' => '1'])->select();
		$mDocuments = M('Documents');

		$map['tmp'] = ['neq', 2];
		//搜索
		if (I('get.sort_id/d')) {
			//查询该分类的下级分类
			$sort_junior = $mSort->where(['pid' => I('get.sort_id/d')])->field('id')->select();
			$sort_list = [I('get.sort_id/d')];
			foreach ($sort_junior as $v) {
				$sort_list[] = $v['id'];
			};
			$map['sort_id'] = ['in', $sort_list];
		}
		if (I('get.start_time')) {
			$map['update_time'] = ['EGT', strtotime(I('get.start_time'))];
		}
		if (I('get.end_time')) {
			$map['update_time'] = ['ELT', strtotime(I('get.end_time'))];
		}
		if (I('get.title/s')) {
			$map['title|abstract'] = ['like', '%' . I('get.title/s') . '%'];
		}

		//分页
		$num = 10; //每页显示多少数据
		$count = $mDocuments->where($map)->count();
		$max_page = ceil($count / $num);
		$new_page = I('get.page/d', 1);
		$new_page = $new_page > $max_page ? $max_page : $new_page;

		$list = $mDocuments->where($map)->field('id,title,sort_id,author,hits,update_time,tmp')->page($new_page, $num)->order('sort desc,id desc')->select();
		foreach ($list as $k => $v) {
			$list[$k]['sort_name'] = '';
			foreach ($sort as $key => $value) {
				if ($value['id'] == $v['sort_id']) {
					$list[$k]['sort_name'] = $value['sname'];
				}
			}
		}
		$url = '?';
		foreach (I('get.', []) as $k => $v) {
			if ($k != 'page') {
				$url .= $k . '=' . $v . '&';
			}
		}
		return $this->fetch('index', [
			'sort' => $sort,
			'list' => $list,
			'count' => $count,
			'max_page' => $max_page,
			'map' => I('get.'),
			'url' => $url,
		]);
	}

	/**
	 * 添加文章
	 */
	public function docu_technique() {
		//创建临时数据
		$mDocu = M('Documents');
		if (I('get.did/d')) {
			$map['id'] = I('get.did/d');
		} else {
			$map['tmp'] = 2;
		}
		$res = $mDocu->where($map)->find();
		if (!$res) {
			$data = [
				'title' => '',
				'sort_id' => 0,
				'author' => '',
				'content' => '',
				'create_time' => time(),
				'sort' => 0,
				'hits' => 0,
				'update_time' => 0,
			];
			$mDocu->add($data);
			$res = $mDocu->where(['tmp' => 2])->find();
		}
		//获取分类
		$mSort = D('api/Sorting');
		$sort_list = $mSort->where(['tmp' => 1])->order('sort desc,id asc')->select();
		$sort_list = $mSort->typeArray($sort_list);

		return $this->fetch('technique', [
			'res' => $res,
			'sort_list' => $sort_list,
		]);
	}

	/**
	 * 更改文章状态
	 */
	public function setTmp() {
		if (IS_AJAX) {
			$did = I('post.did/d');
			$status = I('post.status/d', 1);
			$mDocuments = M('Documents');
			$res = $mDocuments->where(['id' => $did])->setField('tmp', $status);
			return json_encode(['status' => $res ? 'y' : 'n', 'info' => '更新失败']);
		}
	}

	/**
	 * 修改
	 */
	public function update() {
		if (IS_POST) {
			$result = [];
			$mDocuments = M('Documents');
			$map = [
				'id' => ['neq', I('post.did/d')],
				'title' => I('post.title/s'),
				'tmp' => ['neq', 2],
			];
			$res = $mDocuments->field('id')->where($map)->find();
			if ($res) {
				return json_encode(['status' => 'n', 'info' => '该文档标题已经存在！']);
			}

			$data = [
				'title' => I('post.title/s'),
				'sort_id' => I('post.sort_id/d'),
				'author' => I('post.author/s'),
				'content' => $_POST['content'],
				'sort' => I('post.sort/d'),
				'update_time' => NOW_TIME,
				'brief' => I('post.brief/s'),
				'type' => I('post.type/d'),
				'keyword' => I('post.keyword/s'),
				'abstract' => I('post.abstract/s'),
				'comment' => I('post.comment/d'),
				'com_starttime' => strtotime(I('post.com_starttime/d')) ? strtotime(I('post.com_starttime/d')) : NOW_TIME,
				'com_endtime' => strtotime(I('post.com_endtime/d')) ? strtotime(I('post.com_endtime/d')) : 0,
				'tmp' => 3,
			];

			//验证
			$result = $mDocuments->validate(true)->create();
			if (!$result) {
				$res = [
					'status' => 'n',
					'info' => $mDocuments->getError(),
				];
			} else {
				$did = I('post.did/d');
				$res = [
					'status' => $mDocuments->where(['id' => $did])->save($data) ? 'y' : 'n',
					'info' => '数据操作失败！',
				];
			}
			return json_encode($res);
		}
	}

	/**
	 * 缩略图上传
	 */
	public function fileupload() {
		$auth = new \Qiniu\Auth(C('AccessKey'), C('SecretKey'));
		$upToken = $auth->uploadToken(C('bucket'));

		$uploadMgr = new \Qiniu\Storage\UploadManager();
		//自定义文件名
		$key = 'Documents_' . I('post.did/d') . '.png';

		//删除已经存在的图片
		$bucketMgr = new \Qiniu\Storage\BucketManager($auth);
		$bucketMgr->delete(C('bucket'), $key);

		list($ret, $err) = $uploadMgr->putFile($upToken, $key, $_FILES['file']['tmp_name']);

		if ($err) {
			$res = ['status' => 'n', 'info' => '网络错误，请稍后再试！'];
		} else {
			//加入数据库
			$url = C('qn_url') . $ret['key'];
			$mDocuments = M('Documents');
			$data = ['update_time' => $_SERVER['REQUEST_TIME'], 'tmp_image' => $url];
			$res = $mDocuments->where(['id' => I('post.did/d')])->save($data);
			$res = ['status' => $res ? 'y' : 'n', 'info' => '上传失败！'];
		}
		return json_encode($res);
	}

	/**
	 * 文章删除
	 */
	public function delete() {
		if (I('post.did/d')) {
			$mDocuments = M('Documents');
			//删除图片
			$res = $mDocuments->where(['id' => I('post.did/d')])->delete();
			$auth = new \Qiniu\Auth(C('AccessKey'), C('SecretKey'));
			$key = 'Documents_' . I('post.did/d') . '.png';
			$bucketMgr = new \Qiniu\Storage\BucketManager($auth);
			$bucketMgr->delete(C('bucket'), $key);
			return json_encode([
				'status' => $res ? 'y' : 'n',
				'info' => '删除文章失败！',
			]);
		}
	}

	/**
	 * 文档查看
	 */
	public function showDocuments() {
		$did = I('get.did/d');
		$mDocuments = M('Documents');
		$res = $mDocuments->field('id,title,content')->find($did);
		return $this->fetch('show', [
			'res' => $res,
		]);
	}
}
